<?php

namespace App\Console\Commands;

use App\App\Services\VoteCacheService;
use App\Models\VoteCandidate\VoteCandidate;
use Illuminate\Console\Command;

class MakeVoteCache extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vote:cache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'make vote data to redis.';

    public function __construct()
    {
        parent::__construct();
    }


    public function handle(VoteCacheService $cache)
    {
        $activities = $cache->getNeedToCacheActivities();

        if (empty($activities)) {
            $this->line('暂时没有数据需要缓存');
            return;
        }

        $count = $activities->count();

        $successful = 0;
        $need = $count;

        foreach ($activities as $of => $activity) {
            if (!$cache->cached($activity->id)) {
                if ($cache->makeCache($activity->id)) {
                    $successful++;
                }
            } else {
                $need--;
            }
        }

        $this->line(sprintf('本次共%d条数据,需缓存%d条,成功%d条', $count, $need, $successful));
    }
}
